package com.vipheyue.campusrecyce.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.aspsine.swipetoloadlayout.OnLoadMoreListener;
import com.aspsine.swipetoloadlayout.OnRefreshListener;
import com.aspsine.swipetoloadlayout.SwipeToLoadLayout;
import com.vipheyue.campusrecyce.R;
import com.vipheyue.campusrecyce.adapter.BaseRecyclerAdapter;
import com.vipheyue.campusrecyce.adapter.BaseRecyclerViewHolder;
import com.vipheyue.campusrecyce.bean.MyUser;
import com.vipheyue.campusrecyce.bean.ThingBean;
import com.vipheyue.campusrecyce.utils.GsonUtils;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.listener.FindListener;

public class BrowseActivity extends AppCompatActivity  implements OnRefreshListener, OnLoadMoreListener {
    @Bind(R.id.iv_Menu_leftImg)
    ImageView iv_Menu_leftImg;
    @Bind(R.id.tv_Menu_leftTitle)
    TextView tv_Menu_leftTitle;
    @Bind(R.id.rl_menu_left)
    RelativeLayout rl_menu_left;
    @Bind(R.id.tv_Menu_Title)
    TextView tv_Menu_Title;
    @Bind(R.id.iv_menu_rightTitle)
    TextView iv_menu_rightTitle;
    @Bind(R.id.iv_menu_right)
    ImageView iv_menu_right;
    @Bind(R.id.rl_menu_right)
    RelativeLayout rl_menu_right;
    @Bind(R.id.et_fragment0_searchName)
    EditText et_fragment0_searchName;
    @Bind(R.id.btn_fragment0_search)
    Button btn_fragment0_search;
    @Bind(R.id.btn_fragment0_release)
    Button btn_fragment0_release;
    @Bind(R.id.ivSpeed)
    ImageView ivSpeed;
    @Bind(R.id.ivRefresh)
    ImageView ivRefresh;
    @Bind(R.id.swipe_target)
    RecyclerView swipe_target;
    @Bind(R.id.progressbar)
    ProgressBar progressbar;
    @Bind(R.id.ivSuccess)
    ImageView ivSuccess;
    @Bind(R.id.tvLoadMore)
    TextView tvLoadMore;
    @Bind(R.id.swipeToLoadLayout)
    SwipeToLoadLayout swipeToLoadLayout;
    private MyUser currentUser;

    private List<ThingBean> mDatas = new ArrayList<ThingBean>();
    private int nowPageNum = 0;
    private int pageSize = 50;
    private BaseRecyclerAdapter adapter;
    private String category;
    private String searchName;
    private Boolean havedReleaseType;
    private Boolean havedSaleType;
    private Boolean havedBuyType;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_browse);
        ButterKnife.bind(this);
        initview();
    }

    @OnClick({R.id.btn_fragment0_search, R.id.btn_fragment0_release,R.id.rl_menu_left})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_fragment0_search:
                mDatas.clear();
                nowPageNum = 0;
                initData(nowPageNum);

                break;
            case R.id.btn_fragment0_release:
                startActivity(new Intent(this, ReleaseActivity.class));
                break;
            case R.id.rl_menu_left:
                finish();
                break;
        }
    }

    private void addCondition(BmobQuery<ThingBean> query) {
        if (!TextUtils.isEmpty(et_fragment0_searchName.getText().toString().trim())) {
            query.addWhereEqualTo("name", et_fragment0_searchName.getText().toString().trim());
        }
    }



    private void initData(int getNumPage) {
        BmobQuery<ThingBean> query = new BmobQuery<ThingBean>();
        query.setLimit(pageSize); // 限制最多10条数据结果作为一页
        query.setSkip(pageSize * getNumPage); // 忽略前10条数据（即第一页数据结果）
        query.order("-updatedAt");
        query.include("releaseUser");
        if (!TextUtils.isEmpty(category)) {
            query.addWhereEqualTo("category", category);
        }
        if (!TextUtils.isEmpty(searchName)) {
            query.addWhereMatches("name", searchName);
        }

        if (havedReleaseType) {
            query.addWhereEqualTo("releaseUser", currentUser);
        }
//        if (havedSaleType) {
//            query.addWhereEqualTo("releaseUser", currentUser);
//        }
        if (havedBuyType) {
            query.addWhereEqualTo("successfulTenderer", currentUser);
        }

        addCondition(query);
        query.findObjects(this, new FindListener<ThingBean>() {
            @Override
            public void onSuccess(List<ThingBean> object) {
                mDatas.addAll(object);
                nowPageNum = nowPageNum + 1;
                // Call onRefreshComplete when the list has been refreshed.
                stopFresh();
            }

            @Override
            public void onError(int code, String msg) {
                stopFresh();
            }
        });
    }

    private void stopFresh() {
        adapter.notifyDataSetChanged();
        swipeToLoadLayout.setRefreshing(false);
        swipeToLoadLayout.setLoadingMore(false);
    }


    private void initview() {
        currentUser = BmobUser.getCurrentUser(this,MyUser.class);
        category = getIntent().getStringExtra("Category");
        searchName = getIntent().getStringExtra("searchName");
        havedReleaseType = getIntent().getBooleanExtra("HavedRelease", false);
        havedSaleType = getIntent().getBooleanExtra("HavedSale", false);
        havedBuyType = getIntent().getBooleanExtra("HavedBuy", false);
        tv_Menu_Title.setText("APP");
        GridLayoutManager layoutManager = new GridLayoutManager(this, 2);
//        LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        swipe_target.setLayoutManager(layoutManager);//设置显示方式

//        swipe_target.addItemDecoration(new HorizontalDividerItemDecoration.Builder(this).build());// 第一 普通

//        Paint paint = new Paint(); //第二
//        paint.setStrokeWidth(45);
//        paint.setColor(Color.BLUE);
//        paint.setAntiAlias(true);
//        paint.setPathEffect(new DashPathEffect(new float[]{25.0f, 25.0f}, 0));
//        swipe_target.addItemDecoration(new HorizontalDividerItemDecoration.Builder(this)
//                .paint(paint)
//                .showLastDivider().margin(100, 0)
//                .build());


        swipe_target.addItemDecoration(new HorizontalDividerItemDecoration.Builder(this)//第三
                .drawable(R.drawable.divider)//这里可以是图片
                .size(10)
                .build());


//        swipe_target.setAdapter(adapter);//设置适配器
        adapter = new BaseRecyclerAdapter<ThingBean>(this, mDatas, R.layout.activity_item) {
            @Override
            public void init(BaseRecyclerViewHolder holder, ThingBean bean, int position) {
                holder.setText(R.id.tv_schoolName,bean.getLocation());//TODO 这里因该是schoolName
                holder.setCircleImage(BrowseActivity.this,R.id.iv_thingBeanIcon,R.drawable.camera);//TODO 设置一个 默认的 本来和下面一句 是else的

                if (bean.getThingImgs() != null && bean.getThingImgs().size() > 0) {
                    holder.setCircleImage(BrowseActivity.this,R.id.iv_thingBeanIcon,bean.getThingImgs().get(0));
                }
                holder.setText(R.id.tv_release_name,bean.getName());
                holder.setText(R.id.tv_release_price,"¥ "+bean.getPrice());


            }
        };
        adapter.setOnItemClickLinster(new BaseRecyclerAdapter.OnItemClickLinster() {
            @Override
            public void onItemClick(View view, int position) {
                ThingBean job = mDatas.get(position);
                String thingBeanStr = GsonUtils.toJson(job);
                Intent intent = new Intent(BrowseActivity.this, DetailActivity.class);
                intent.putExtra("thingBeanStr", thingBeanStr);
                startActivity(intent);
            }
        });
        swipe_target.setAdapter(adapter);//设置适配器

//        swipeToLoadLayout.setSwipeStyle(SwipeToLoadLayout.STYLE.ABOVE);
        swipeToLoadLayout.setOnRefreshListener(this);
        swipeToLoadLayout.setOnLoadMoreListener(this);

        swipeToLoadLayout.post(new Runnable() {
            @Override
            public void run() {
                swipeToLoadLayout.setRefreshing(true);
            }
        });
    }
    @Override
    public void onLoadMore() {
        initData(nowPageNum);
    }

    @Override
    public void onRefresh() {
        mDatas.clear();
        nowPageNum = 0;
        initData(nowPageNum);
    }
  
}
